package com.lyy.dao.impl;

import com.lyy.dao.IAccountDao;
import com.lyy.domain.Account;
import com.lyy.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Repository(value = "accountDaoImpl2")
public class AccountDaoImpl2 implements IAccountDao {


    @Autowired
    private QueryRunner queryRunner;

    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public void insert(Account account) {
        try {
            Connection connection=connectionUtils.getConnection();
            String sql="INSERT INTO account(id,`name`,money) VALUE(MD5(UUID()),?,?)";
            Object[] params={account.getName(),account.getMoney()};
            queryRunner.update(connection,sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("新增记录出错,e"+e.toString());
        }
    }

    @Override
    public List<Account> findAll() {
        try {
            Connection connection=connectionUtils.getConnection();
            String sql="SELECT * FROM account";
            List list = (List) queryRunner.query(connection,sql, new BeanListHandler(Account.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询全部记录出错,e"+e.toString());
        }
    }

    @Override
    public Account findById(String id) {
        try {
            Connection connection=connectionUtils.getConnection();
            String sql="SELECT * FROM account WHERE id=?";
            Account account = queryRunner.query(connection,sql, new BeanHandler<>(Account.class), id);
            return account;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询指定记录出错,e"+e.toString());
        }
    }

    @Override
    public void delete(String id) {
        try {
            Connection connection=connectionUtils.getConnection();
            String sql="DELETE FROM account WHERE id=?";
            queryRunner.update(connection,sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("删除指定记录出错,e"+e.toString());
        }
    }

    @Override
    public void updateMoney(String id,float money) {
        try {
            Connection connection=connectionUtils.getConnection();
            String sql="UPDATE account SET money=? WHERE id=?";
            queryRunner.update(connection,sql,new Object[]{money,id});
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("更新指定记录出错,e"+e.toString());
        }
    }

}
